<template>
    <div class="king-editor">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default"/>
        <Editor style="height: 666px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated"/>
    </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { nextTick, reactive, ref, useTemplateRef, shallowRef, onBeforeUnmount, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 定义双向数据绑定
const valueHtml = defineModel({ default: '' })

watch(() => valueHtml.value, (val) => {
    nextTick(() => {
        console.log('valueHtml.value', val)
    })
})

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        'uploadImage': {
            maxNumber: 5,
            maxFileSize: 1024 * 1024 * 2,
            fieldName: 'file',
            server: `${import.meta.env.VITE_UPLOAD_IMAGE_URL}`,
            customInsert: (res, insertFn) => {
                insertFn(res.data.url, '图片')
            }
        },
        'uploadVideo': {
            maxNumber: 5,
            maxFileSize: 1024 * 1024 * 10,
            fieldName: 'file',
            server: `${import.meta.env.VITE_UPLOAD_VIDEO_URL}`,
            customInsert: (res, insertFn) => {
                insertFn(res.data.url, '视频')
            }
        }
    }
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const handleCreated = (editor) => {
    editorRef.value = editor
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
</script>

<style lang="less" scoped>
.king-editor {
    border: 1px solid #ccc;
    h1 {
        span {
            font-size: 24px !important;
        }

    }
}

</style>